package com.hdl.school.schoolcontroller;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.PopupMenu;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hdl.school.adapter.MediaAdapter;
import com.hdl.school.application.MyApplication;
import com.hdl.school.bean.PlanTaskSource;
import com.hdl.school.service.CloudCtrlService;
import com.hdl.school.service.MqttService;
import com.hdl.school.service.OuterMqttService;
import com.hdl.school.service.PlayerService;
import com.hdl.school.service.Service1;
import com.hdl.school.service.TCPClientService;
import com.hdl.school.service.TaskService;
import com.hdl.school.utils.BroadcastAction;
import com.hdl.school.utils.SystemUtil;
import com.hdl.school.utils.TCWManager;
import com.hdl.school.utils.TimeUtil;
import com.hdl.school.utils.USBSerialManager;
import com.leectrl.IOTServer;
import com.zxm.libinstaller.helper.ApkInstaller;
import com.zxm.libinstaller.info.InstallState;
import com.zxm.libinstaller.listener.OnInstallStateListener;

import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;


public class MainActivity extends CardSlotActivity implements PopupMenu.OnMenuItemClickListener {
    private MainReceiver mainReceiver;

    private MediaAdapter mediaAdapter;

    @ViewInject(R.id.versionname)
    private TextView versioNname;

    @ViewInject(R.id.roomname)
    private TextView roomName;

    @ViewInject(R.id.settings)
    private TextView settings;

    @ViewInject(R.id.time)
    private TextView time;

    @ViewInject(R.id.tasklist)
    private RecyclerView taskList;

    @ViewInject(R.id.notask)
    private TextView notask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        x.view().inject(this);
        try {
            versioNname.setText("(" + SystemUtil.getVersionName(MainActivity.this) + ")");
        } catch (Exception e) {
            e.printStackTrace();
        }

        Intent intent = new Intent(this, Service1.class);
        startService(intent);
        Intent playerIntent = new Intent(MainActivity.this, PlayerService.class);
        startService(playerIntent);
        Intent taskIntent = new Intent(MainActivity.this, TaskService.class);
        startService(taskIntent);
        Intent mqttServiceIntent = new Intent(MainActivity.this, MqttService.class);
        startService(mqttServiceIntent);
        //原来正常启动不会启动
        //if(!BuildConfig.DEBUG){
        //liuyong 改成正常运行就启动
        if(!BuildConfig.DEBUG){
            Intent intent1 = new Intent("com.leectrl.app.checkAlive");
            intent1.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
            intent1.putExtra("checkPackageName", "com.hdl.school.schoolcontroller");
            sendBroadcast(intent1);
        }

        //刷新当前时间
        Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                handler.sendEmptyMessage(0);
            }
        };
        timer.schedule(task, 0, 60000);
        mediaAdapter = new MediaAdapter(this, new ArrayList<PlanTaskSource>());
        taskList.setLayoutManager(new LinearLayoutManager(this));
        taskList.setAdapter(mediaAdapter);
        mainReceiver = new MainReceiver();
        IntentFilter intentFilter = new IntentFilter();
        //获取到课室信息
        intentFilter.addAction(BroadcastAction.ACTION_ROOMNAME);
        //任务列表变化
        intentFilter.addAction(BroadcastAction.ACTION_TASKLIST);
        intentFilter.addAction(BroadcastAction.ACTION_MEDIA_ENVENT);
        registerReceiver(mainReceiver, intentFilter);

        settings.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //创建弹出式菜单对象（最低版本11）
                PopupMenu popup = new PopupMenu(MainActivity.this, view);//第二个参数是绑定的那个view
                //获取菜单填充器
                MenuInflater inflater = popup.getMenuInflater();
                //填充菜单
                inflater.inflate(R.menu.menu_main, popup.getMenu());
                //绑定菜单项的点击事件
                popup.setOnMenuItemClickListener(MainActivity.this);
                //显示(这一行代码不要忘记了)
                popup.show();
            }
        });
        SharedPreferences sharedPreferences=getSharedPreferences("school_iot", 0);
        boolean cloudCtrl=sharedPreferences.getBoolean("CLOUDCTRL",false);
        if(cloudCtrl){
            Intent cloudCtrlService = new Intent(MainActivity.this, CloudCtrlService.class);
            startService(cloudCtrlService);
        }
        String outerMqtt=sharedPreferences.getString("c_setting_mqtt",null);
        if(outerMqtt!=null){
            JSONObject mqttConfig=JSON.parseObject(outerMqtt);
            if(mqttConfig!=null&&mqttConfig.containsKey("enable")&&mqttConfig.getString("enable").equals("on")){
                Intent outerMqttService = new Intent(MainActivity.this, OuterMqttService.class);
                startService(outerMqttService);
            }

        }
        String extraSerial=sharedPreferences.getString("c_setting_extraSerial",null);
        if(extraSerial!=null){
            JSONObject extraSerialConfig=JSON.parseObject(extraSerial);
            if(extraSerialConfig!=null&&extraSerialConfig.containsKey("enable")&&extraSerialConfig.getBoolean("enable")){
                Intent outerMqttService = new Intent(MainActivity.this, TCPClientService.class);
                startService(outerMqttService);
            }

        }


//        Intent timerTaskService = new Intent(MainActivity.this, TimerTaskService.class);
//        startService(timerTaskService);
        Intent webService = new Intent(MainActivity.this, IOTServer.class);
        startService(webService);
        //是否跳转到串口调试页面
        if(BuildConfig.DEBUG){
            Intent logIntent=new Intent(MainActivity.this,USBSerialLogActivity.class);
            startActivity(logIntent);
        }else{
            checkInstallAutoUpdgradeApp();
        }
        handler.sendEmptyMessageDelayed(1, 3000);
        test();
    }

    private void test(){
//        if(BuildConfig.DEBUG){
//            new Thread(new Runnable() {
//                @Override
//                public void run() {
//                    try {
//                        DbUtil.getInstance().dropTable(ZigbeeDevice.class);
//                    ZigbeeDevice zigbeeDevice=new ZigbeeDevice();
//                    zigbeeDevice.setDeviceType("zigbee-switcher");
//                    zigbeeDevice.setDeviceName("第1路,第2路");
//                    zigbeeDevice.setLineName("第1路,第2路");
//                    zigbeeDevice.setDevicekey("1,2");
//                    zigbeeDevice.setMac("42452626533");
//                    zigbeeDevice.setEnableTag("1,1");
//                    zigbeeDevice.setCreateTime(new Date(System.currentTimeMillis()));
//
//                        DbUtil.getInstance().save(zigbeeDevice);
//                        ZigbeeDevice zigbeeDevice2=new ZigbeeDevice();
//                        zigbeeDevice2.setDeviceType("zigbee-switcher");
//                        zigbeeDevice2.setDeviceName("第3路,第4路");
//                        zigbeeDevice2.setLineName("第3路,第4路");
//                        zigbeeDevice2.setDevicekey("3,4");
//                        zigbeeDevice2.setMac("42452626534");
//                        zigbeeDevice2.setEnableTag("1,1");
//                        zigbeeDevice2.setCreateTime(new Date(System.currentTimeMillis()));
//
//                        DbUtil.getInstance().save(zigbeeDevice2);
//                        ZigbeeDevice zigbeeDevice3=new ZigbeeDevice();
//                        zigbeeDevice3.setDeviceType("zigbee-switcher");
//                        zigbeeDevice3.setDeviceName("第5路,第6路");
//                        zigbeeDevice3.setLineName("第5路,第6路");
//                        zigbeeDevice3.setDevicekey("5,6");
//                        zigbeeDevice3.setMac("42452626535");
//                        zigbeeDevice3.setEnableTag("1,1");
//                        zigbeeDevice3.setCreateTime(new Date(System.currentTimeMillis()));
//
//                        DbUtil.getInstance().save(zigbeeDevice3);
//                        for(int i=1;i<=8;i++){
//                            ZigbeeDevice zigbeeDevice4=new ZigbeeDevice();
//                            zigbeeDevice4.setDeviceType("zigbee-curtain");
//                            zigbeeDevice4.setDeviceName("窗"+i);
//                            zigbeeDevice4.setLineName("窗"+i);
//                            zigbeeDevice4.setDevicekey(String.valueOf(i));
//                            zigbeeDevice4.setMac(String.valueOf(424526+i));
//                            zigbeeDevice4.setEnableTag("1");
//                            zigbeeDevice4.setCreateTime(new Date(System.currentTimeMillis()));
//                            DbUtil.getInstance().save(zigbeeDevice4);
//                        }
//
//
//                    } catch (DbException e) {
//                        e.printStackTrace();
//                    }
//                }
//            }).start();
//
//        }
    }

    private void checkInstallAutoUpdgradeApp() {
        if (!isAvilible(this, "com.leectrl.autoupdate")) {
            String installApk = Environment.getExternalStorageDirectory().getAbsolutePath() + "/download/";
            File dir = new File(installApk);

            if (!dir.exists()) {
                dir.mkdir();
            }
            File apkFile = new File(installApk + "autoupdate.apk");
            if (apkFile.exists()) {
                apkFile.delete();
            }
            InputStream is = getResources().openRawResource(R.raw.autoupdate);
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(installApk + "autoupdate.apk");
                byte[] buffer = new byte[8192];
                int count = 0;

                while ((count = is.read(buffer)) > 0) {
                    fos.write(buffer, 0, count);
                }
                fos.close();
                is.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }


            ApkInstaller autoInstaller = ApkInstaller.getInstance(this);
            autoInstaller.setInstallStateListener(new OnInstallStateListener() {
                @Override
                public void onInstallStart(String filePath) {

                }

                @Override
                public void onInstallComplete() {
                    Intent intent1 = new Intent("com.leectrl.app.checkAlive");
                    intent1.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
                    intent1.putExtra("checkPackageName", "com.hdl.school.schoolcontroller");
                    sendBroadcast(intent1);
                }

                @Override
                public void onInstallFailed(InstallState state) {

                }

                @Override
                public void onAccessibilitySwitchChanged() {

                }
            });
            autoInstaller.startInstall(apkFile.getAbsolutePath());
        }
    }


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    String nowStr = ((MyApplication) getApplicationContext()).getCurrentTime();
                    time.setText(nowStr.substring(0, nowStr.length() - 3));
                    if((new Date()).getYear()>=120){
                        if (nowStr.substring(12, 17).equals("00:00")||nowStr.substring(12, 17).equals("06:00")) {
                            TCWManager.getInstance(MainActivity.this).reboot();
                        }
                    }

                    break;
                case 1:
                    usbSerialManager.attachContext(MainActivity.this);
                    break;
            }
        }
    };


    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            if (mainReceiver != null) {
                unregisterReceiver(mainReceiver);
            }
            USBSerialManager.getInstence().dettachContext(MainActivity.this);
        }catch(Exception e){
            e.printStackTrace();
        }

    }


    @Override
    public boolean onMenuItemClick(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.service:
                Intent intent2 = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
                startActivity(intent2);
                break;
            case R.id.date:
                Intent intent4 = new Intent(Settings.ACTION_DATE_SETTINGS);
                startActivity(intent4);
                break;
            case R.id.config:
                startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
                break;
        }
        return true;
    }

    private boolean isAvilible(Context context, String packageName) {
        final PackageManager packageManager = context.getPackageManager();
        // 获取所有已安装程序的包信息
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        for (int i = 0; i < pinfo.size(); i++) {
            if (pinfo.get(i).packageName.equalsIgnoreCase(packageName))
                return true;
        }
        return false;
    }




    class MainReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BroadcastAction.ACTION_ROOMNAME.equals(action)) {
                roomName.setText(intent.getStringExtra("room_name"));
            } else if (BroadcastAction.ACTION_TASKLIST.equals(action)) {
                String tasksStr = intent.getStringExtra("tasks");
                List<PlanTaskSource> tasks = JSON.parseArray(tasksStr, PlanTaskSource.class);
                long now = TimeUtil.currentStap();
                for (PlanTaskSource planTaskSource : tasks) {
                    planTaskSource.setInPlaying(now >= TimeUtil.timeInToday(planTaskSource.getPlayStartTime()) && now < TimeUtil.timeInToday(planTaskSource.getPlayEndTime()));
                }
                mediaAdapter.setTasks(tasks);
                mediaAdapter.notifyDataSetChanged();
                if (tasks.size() == 0) {
                    taskList.setVisibility(View.INVISIBLE);
                    notask.setVisibility(View.VISIBLE);
                } else {
                    notask.setVisibility(View.INVISIBLE);
                    taskList.setVisibility(View.VISIBLE);
                }
            } else if (BroadcastAction.ACTION_MEDIA_ENVENT.equals(action)) {
                String tasksStr = intent.getStringExtra("tasks");
                List<PlanTaskSource> tasks = JSON.parseArray(tasksStr, PlanTaskSource.class);
                if (tasks != null) {
                    long now = TimeUtil.currentStap();
                    for (PlanTaskSource planTaskSource : tasks) {
                        planTaskSource.setInPlaying(now >= TimeUtil.timeInToday(planTaskSource.getPlayStartTime()) && now < TimeUtil.timeInToday(planTaskSource.getPlayEndTime()));
                    }
                    mediaAdapter.setTasks(tasks);
                    mediaAdapter.notifyDataSetChanged();
                }
            }
        }
    }


}
